using Sage.Http.Models;
using System.Text;

namespace Sage.Http.Authentication
{
    /// <summary>
    /// API密钥认证提供者
    /// </summary>
    /// <remarks>
    /// 初始化API密钥认证提供者
    /// </remarks>
    /// <param name="apiKey">API密钥</param>
    /// <param name="headerName">头部名称，默认为"X-API-Key"</param>
    /// <param name="parameterName">查询参数名称，如果指定则添加到查询字符串中</param>
    public class ApiKeyAuthProvider(string apiKey, string headerName = "X-API-Key", string? parameterName = null) : IAuthenticationProvider
    {
        private readonly string _apiKey = apiKey ?? throw new ArgumentNullException(nameof(apiKey));
        private readonly string _headerName = headerName ?? throw new ArgumentNullException(nameof(headerName));
        private readonly string? _parameterName = parameterName;

        /// <summary>
        /// 获取API密钥
        /// </summary>
        public string ApiKey => _apiKey;

        /// <summary>
        /// 获取API密钥位置
        /// </summary>
        public ApiKeyLocation Location => string.IsNullOrEmpty(_parameterName) ? ApiKeyLocation.Header : ApiKeyLocation.QueryParameter;

        /// <summary>
        /// 获取名称（头部名称或参数名称）
        /// </summary>
        public string Name => string.IsNullOrEmpty(_parameterName) ? _headerName : _parameterName;

        /// <summary>
        /// 对请求进行身份验证
        /// </summary>
        /// <param name="request">HTTP请求</param>
        public Task AuthenticateRequest(HttpRequestMessage request)
        {
            ArgumentNullException.ThrowIfNull(request);

            // 添加到请求头
            request.Headers.Add(_headerName, _apiKey);

            // 如果指定了参数名称，添加到查询字符串
            if (!string.IsNullOrEmpty(_parameterName) && request.RequestUri != null)
            {
                var uriBuilder = new UriBuilder(request.RequestUri);
                var query = ParseQueryString(uriBuilder.Query);
                query[_parameterName] = _apiKey;
                uriBuilder.Query = BuildQueryString(query);
                request.RequestUri = uriBuilder.Uri;
            }

            return Task.CompletedTask;
        }

        /// <summary>
        /// 解析查询字符串为字典
        /// </summary>
        /// <param name="queryString">查询字符串</param>
        /// <returns>查询参数字典</returns>
        private static Dictionary<string, string> ParseQueryString(string queryString)
        {
            return Utilities.HttpUtilities.ParseQueryString(queryString);
        }

        /// <summary>
        /// 构建查询字符串
        /// </summary>
        /// <param name="parameters">查询参数字典</param>
        /// <returns>查询字符串</returns>
        private static string BuildQueryString(Dictionary<string, string> parameters)
        {
            return Utilities.HttpUtilities.BuildQueryString(parameters);
        }
    }
}
